import express from 'express';
import { executeInvestigationWorkflow } from '../mastra/index';
import { 
  CaseGenerationRequestSchema, 
  SuspectDialogueRequestSchema, 
  DeductionSubmissionSchema 
} from '../mastra/types/game';

const router = express.Router();

/**
 * 健康检查接口
 */
router.get('/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    message: '赛博侦探游戏AI服务运行正常',
    timestamp: new Date().toISOString()
  });
});

/**
 * 开始新案件
 * POST /api/game/start
 */
router.post('/game/start', async (req, res) => {
  try {
    console.log('收到开始新案件请求:', req.body);
    
    // 验证请求参数
    const caseGenerationRequest = CaseGenerationRequestSchema.parse(req.body);
    
    // 生成游戏ID
    const gameId = `game-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    
    // 执行调查工作流
    const result = await executeInvestigationWorkflow({
      action: 'start_case',
      caseGenerationRequest,
      gameId
    });
    
    if (result.success) {
      res.json({
        success: true,
        message: '案件生成成功',
        gameId,
        data: result.caseData,
        gameState: result.gameState
      });
    } else {
      res.status(400).json({
        success: false,
        message: result.message,
        error: 'CASE_GENERATION_FAILED'
      });
    }
    
  } catch (error) {
    console.error('开始新案件失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 与嫌疑人对话
 * POST /api/game/chat
 */
router.post('/game/chat', async (req, res) => {
  try {
    console.log('收到嫌疑人对话请求:', req.body);
    
    const { gameId, ...dialogueData } = req.body;
    
    if (!gameId) {
      return res.status(400).json({
        success: false,
        message: '缺少游戏ID',
        error: 'MISSING_GAME_ID'
      });
    }
    
    // 验证请求参数
    const suspectDialogueRequest = SuspectDialogueRequestSchema.parse(dialogueData);
    
    // 执行调查工作流
    const result = await executeInvestigationWorkflow({
      action: 'chat_suspect',
      suspectDialogueRequest,
      gameId
    });
    
    if (result.success) {
      res.json({
        success: true,
        message: '对话成功',
        data: result.response,
        gameState: result.gameState
      });
    } else {
      res.status(400).json({
        success: false,
        message: result.message,
        error: 'CHAT_FAILED'
      });
    }
    
  } catch (error) {
    console.error('嫌疑人对话失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 提交推理结果
 * POST /api/game/submit
 */
router.post('/game/submit', async (req, res) => {
  try {
    console.log('收到推理结果提交:', req.body);
    
    const { gameId, ...deductionData } = req.body;
    
    if (!gameId) {
      return res.status(400).json({
        success: false,
        message: '缺少游戏ID',
        error: 'MISSING_GAME_ID'
      });
    }
    
    // 验证请求参数
    const deductionSubmission = DeductionSubmissionSchema.parse(deductionData);
    
    // 执行调查工作流
    const result = await executeInvestigationWorkflow({
      action: 'submit_deduction',
      deductionSubmission,
      gameId
    });
    
    if (result.success) {
      res.json({
        success: true,
        message: result.message,
        data: result.result,
        gameState: result.gameState
      });
    } else {
      res.status(400).json({
        success: false,
        message: result.message,
        error: 'SUBMISSION_FAILED'
      });
    }
    
  } catch (error) {
    console.error('提交推理结果失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 获取游戏状态
 * GET /api/game/status/:gameId
 */
router.get('/game/status/:gameId', async (req, res) => {
  try {
    const { gameId } = req.params;
    
    console.log('获取游戏状态:', gameId);
    
    // 执行调查工作流
    const result = await executeInvestigationWorkflow({
      action: 'get_status',
      gameId
    });
    
    if (result.success) {
      res.json({
        success: true,
        message: '获取状态成功',
        gameState: result.gameState,
        gameData: result.gameData
      });
    } else {
      res.status(404).json({
        success: false,
        message: result.message,
        error: 'GAME_NOT_FOUND'
      });
    }
    
  } catch (error) {
    console.error('获取游戏状态失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 获取案件列表（用于测试）
 * GET /api/game/cases
 */
router.get('/game/cases', async (req, res) => {
  try {
    // 返回预定义的案件模板信息
    const caseTemplates = [
      {
        id: 'office-poison',
        title: '办公室咖啡毒杀案',
        difficulty: 'easy',
        description: '科技公司办公室发生的毒杀案件',
        estimatedTime: '10-15分钟'
      },
      {
        id: 'library-mystery',
        title: '图书馆密室案',
        difficulty: 'easy',
        description: '大学图书馆古籍室的神秘死亡',
        estimatedTime: '10-15分钟'
      },
      {
        id: 'elevator-murder',
        title: '密室电梯谋杀案',
        difficulty: 'normal',
        description: '高档写字楼电梯内的精心谋杀',
        estimatedTime: '15-20分钟'
      },
      {
        id: 'hotel-death',
        title: '酒店房间离奇死亡',
        difficulty: 'normal',
        description: '五星级酒店套房的过敏死亡案',
        estimatedTime: '15-20分钟'
      },
      {
        id: 'time-trap',
        title: '时间错位杀人案',
        difficulty: 'hard',
        description: '利用时间差制造的完美犯罪',
        estimatedTime: '20-25分钟'
      },
      {
        id: 'identity-swap',
        title: '双重身份谋杀案',
        difficulty: 'hard',
        description: '艺术画廊的身份迷局',
        estimatedTime: '20-25分钟'
      }
    ];
    
    res.json({
      success: true,
      message: '获取案件列表成功',
      data: caseTemplates
    });
    
  } catch (error) {
    console.error('获取案件列表失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 重置游戏（用于测试）
 * DELETE /api/game/reset/:gameId
 */
router.delete('/game/reset/:gameId', async (req, res) => {
  try {
    const { gameId } = req.params;
    
    console.log('重置游戏:', gameId);
    
    // 这里应该调用清理游戏状态的函数
    // 由于我们的游戏状态存储在工作流内部，这里只是返回成功响应
    
    res.json({
      success: true,
      message: '游戏重置成功',
      gameId
    });
    
  } catch (error) {
    console.error('重置游戏失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 获取游戏统计信息
 * GET /api/game/stats/:gameId
 */
router.get('/game/stats/:gameId', async (req, res) => {
  try {
    const { gameId } = req.params;
    
    console.log('获取游戏统计:', gameId);
    
    // 获取游戏状态
    const result = await executeInvestigationWorkflow({
      action: 'get_status',
      gameId
    });
    
    if (result.success && result.gameState) {
      const stats = {
        gameId,
        phase: result.gameState.phase,
        timeRemaining: result.gameState.timeRemaining,
        conversationCount: result.gameState.conversationCount,
        discoveredClues: result.gameState.discoveredClues.length,
        currentScore: result.gameState.score,
        suspectInteractions: result.gameState.suspectInteractions,
        startTime: new Date().toISOString(), // 这里应该从实际数据获取
      };
      
      res.json({
        success: true,
        message: '获取统计信息成功',
        data: stats
      });
    } else {
      res.status(404).json({
        success: false,
        message: '游戏不存在',
        error: 'GAME_NOT_FOUND'
      });
    }
    
  } catch (error) {
    console.error('获取游戏统计失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

/**
 * 错误处理中间件
 */
router.use((error: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error('API路由错误:', error);
  
  if (error.name === 'ZodError') {
    return res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      error: 'VALIDATION_ERROR',
      details: error.errors
    });
  }
  
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: error.message || '未知错误'
  });
});

export default router;